package interpreter;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class OneParameterVariation {
	static Map<String,Boolean> explored = new HashMap<String,Boolean>();
	
	private static String getCode(int []params, int zeroIndex) {
		String code = zeroIndex + "_";
		for(int i=0; i<params.length; i++) {
			code += RealResult.params_codes[i] + "_" + params[i];
		}
		return code;
	}

	public static String doFilesAndPlot(String folder, int zeroIndex, int []params, ArrayList<RealResult> realResults) {
		String gnuPlotScript = "";
		String code = getCode(params, zeroIndex);
		if(explored.containsKey(code)) {
			return "";
		}
		explored.put(code, true);
		
		// Look for all other matching results
		ArrayList<RealResult> matching = new ArrayList<RealResult>();
		for(RealResult r : realResults) {
			if(r.matches(params)) {
				matching.add(r);
			}
		}
		
		if(matching.size() > 2) {
			// At least 2 other in common
			// Dump data
			
			Comparator<RealResult> myComp = new CompareRealResult(zeroIndex);
			Collections.sort(matching, myComp);
			
			// Construct the filename
			String importantParts = "one";
			for(int i=0; i<params.length; i++) {
				importantParts += "_" + RealResult.params_codes[i];
				if(params[i] == 0) {
					importantParts += "xx";
				} else {
					importantParts += params[i];
				}
			}
			String filename = importantParts + ".txt";
			String path = folder + (folder.endsWith("/") ? filename : "/" + filename);
			System.err.println("MATCHING FILENAME: " + path);
			
			try {
				FileWriter fstream = new FileWriter(path, false);
				BufferedWriter outFile = new BufferedWriter(fstream);
				
				for(RealResult r : matching) {
					String line = "";
					line += r.params[zeroIndex] + ",";
					line += r.Tmean + ",";
					line += r.TstdDev + ",";
					line += r.confidence1Tmin + ",";
					line += r.confidence1Tmax + ",";
					line += r.confidence2Tmin + ",";
					line += r.confidence2Tmax + ",";
					line += r.ARTmean + ",";
					line += r.ARTstdDev + ",";
					line += r.confidence1ARTmin + ",";
					line += r.confidence1ARTmax + ",";
					line += r.confidence2ARTmin + ",";
					line += r.confidence2ARTmax + ",";
					line += r.MRTmean + ",";
					line += r.MRTstdDev + ",";
					line += r.confidence1MRTmin + ",";
					line += r.confidence1MRTmax + ",";
					line += r.confidence2MRTmin + ",";
					line += r.confidence2MRTmax;
					outFile.write(line);
					outFile.newLine();
				}
				
				int minX = matching.get(0).params[zeroIndex];
				int maxX = matching.get(matching.size()-1).params[zeroIndex];
				
				gnuPlotScript += "\n\n" + gnuplot(filename, params, zeroIndex, minX, maxX);
				
				outFile.close();
			} catch (Exception e) {
				System.out.println("Can't write to experiment file!!!");
				e.printStackTrace();
			}
		}
		
		return gnuPlotScript;
	}
	
	private static String gnuplot(String txtFileName, int[] params, int zeroIndex, int minX, int maxX) {
		String importantParts = txtFileName.replaceAll("\\.txt", "");
		String title = "";
		boolean is_first_in_title = true;
		for(int i=0; i<params.length; i++) {
			if(params[i] != 0) {
				if(!is_first_in_title) {
					title += ", ";
				} else {
					is_first_in_title = false;
				}
				title += RealResult.params_codes[i] + ": " + params[i];
			}
		}
		String xlabel = RealResult.params_names[zeroIndex];
		String xrange = "[0:"+(maxX+1)+"]";
	return
"set autoscale\n"+
"unset log\n"+
"unset label\n"+
"set xtic auto\n"+
"set ytic auto\n"+
"set title \"Throughput"+title+"\" font \"Calibri,15\"\n"+
"set xlabel \""+xlabel+"\"\n"+
"set ylabel \"Throughput (q/s)\"\n"+
"set yrange[0:]\n"+
"set xrange"+xrange+"\n"+
"set terminal png\n"+
"set output \""+importantParts+"_Throughput.png\"\n"+
"set datafile separator \",\"\n"+
"\n"+
"set key bottom Left\n"+
"plot	\""+txtFileName+"\" using 1:2:6:7 title \"90%\" with yerrorlines ,\\\n"+
"		\""+txtFileName+"\" using 1:2:4:5 title \"80%\" with yerrorlines\n"+
"\n"+
"\n"+		
"set autoscale\n"+
"unset log\n"+
"unset label\n"+
"set xtic auto\n"+
"set ytic auto\n"+
"set title \"Response Times - "+title+"\" font \"Calibri,15\"\n"+
"set xlabel \""+xlabel+"\"\n"+
"set ylabel \"Response time (ms)\"\n"+
"set yrange[0:]\n"+
"set xrange"+xrange+"\n"+
"set terminal png\n"+
"set output \""+importantParts+"_RT.png\"\n"+
"set datafile separator \",\"\n"+
"set key bottom Left\n"+
"plot	\""+txtFileName+"\" using 1:8:12:13 title \"Average 90%\" with yerrorlines ,\\\n"+
"		\""+txtFileName+"\" using 1:8:10:11 title \"Average 80%\" with yerrorlines ,\\\n"+
"		\""+txtFileName+"\" using 1:14:18:19 title \"Mean 90%\" with yerrorlines ,\\\n"+
"		\""+txtFileName+"\" using 1:14:16:17 title \"Mean 80%\" with yerrorlines \n"+
"\n";	
	}
}
